package com.wenlong.dao;

import com.wenlong.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 苏文龙
 * @version 1.0
 */

/**
 * Druid 连接池
 * dbutils 工具
 * 抽象出 SQL 语句,使具体的 dao层专注具体的 SQL 命令
 * @param <T>
 */
public abstract class BashDao<T> {
    private QueryRunner queryRunner = new QueryRunner();

    /**
     * @param sql    sql 语句
     * @param params 查询参数
     * @return return -1,查询失败或无结果,否则返回影响行数
     */
    public int update(String sql, Object... params) {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            int affectRows = 0;
            affectRows = queryRunner.update(connection, sql, params);
            return affectRows;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> T queryForOne(String sql, Class<T> clazz, Object... params) {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.query(connection, sql, new BeanHandler<>(clazz), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public <T> List<T> queryForMulti(String sql, Class<T> calzz, Object... params) {
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return queryRunner.query(connection, sql, new BeanListHandler<>(calzz), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Object queryForScalar(String sql,Object... params){
        Connection connection = null;
        connection = JdbcUtils.getConnection();
        try {
            return queryRunner.query(connection, sql, new ScalarHandler<>(), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
